//
//  ZBAppLifecycleManager.m
//  ZBPlatform
//
//  Created by xzb on 2018/10/9.
//

#import "ZBAppLifecycleManager.h"
#import "ZBAppLifecycle.h"

@interface ZBAppLifecycleManager ()

@property (nonatomic, strong) NSMutableArray *modules;

@end

@implementation ZBAppLifecycleManager

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static id instance;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

+ (void)registerAllLib
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"generate_all_lib" ofType:@""];
    
    if (path.length < 1) {
        return;
    }
    NSString *content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSArray *libs = [content componentsSeparatedByString:@"./"];
    if (libs.count  < 0 ) {
        return;
    }
    for (NSString *lib in libs) {
        [[ZBAppLifecycleManager sharedInstance] registerModule:lib config:nil];
    }
}

- (void)registerModule:(NSString *)moduleName config:(NSDictionary *)config
{
    if (moduleName.length < 1) {
        return;
    }
    Class class = NSClassFromString([NSString stringWithFormat:@"%@Lifecycle",moduleName]);
    if (!class) {
        return;
    }
    id<ZBAppLifecycle> module = [[class alloc] initWithConfig:config];
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.modules addObject:module];
        });
    } else {
        [self.modules addObject:module];
    }
}

- (void)addModule:(NSString *)moduleName
{
    Class class = NSClassFromString(moduleName);
    if (!class) {
        return;
    }
    id<ZBAppLifecycle> module = [[class alloc] initWithConfig:@{}];
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.modules addObject:module];
        });
    } else {
        [self.modules addObject:module];
    }
}
- (void)enumerateModulesUsingBlock:(__attribute__((noescape)) void (^)(id module, BOOL *stop))block
{
    [self.modules enumerateObjectsWithOptions:0
                                   usingBlock:^(id _Nonnull module, NSUInteger idx, BOOL * _Nonnull stop) {
                                       block(module, stop);
                                   }];
}

- (NSMutableArray *)modules
{
    if (!_modules){
        _modules = [[NSMutableArray alloc] init];
    }
    return _modules;
}
@end
